<template>
  <el-container>
    <el-header style="padding: 0;height: 35px;">
      <el-row style="display: flex; align-items: center;">
        <el-col :span="10">
          <el-button
            type="primary"
            size="mini"
            @click="batchSelectionRow('odd')"
          >{{ selectMode !== 'odd' ? '选中奇数行' : '取消选中' }}</el-button>
          <el-button
            type="primary"
            size="mini"
            @click="batchSelectionRow('even')"
          >{{ selectMode !== 'even' ? '选中偶数行' : '取消选中' }}</el-button>
        </el-col>
        <el-col :span="8">
          <!--<div style="display: inline-block">
            <div style="width: 10px;height: 10px;background-color: #32CD32; display: inline-block; margin-right: 10px" />
            <span style="margin-right: 20px">已关联户型</span>
          </div>
          <div style="display: inline-block">
            <div style="width: 10px;height: 10px;background-color: #d5f60c; display: inline-block; margin-right: 10px" />
            <span style="margin-right: 20px">已关联平面图</span>
          </div>-->
          <div style="display: inline-block">
            <div style="width: 10px;height: 10px;background-color: #aa0614; display: inline-block; margin-right: 10px" />
            <span style="margin-right: 20px">达售层</span>
          </div>
        </el-col>
      </el-row>
    </el-header>
    <el-main id="mainId" v-loading="loading" style="padding: 0;">
      <div style="overflow-x: auto;" :style="{ width: mainInnerWidth }">
        <div v-if="hasUnit" style="height: 25px;">
          <table style="border-spacing: 0;">
            <tr style="height: 25px;line-height: 25px">
              <th style="border:1px solid #ccc;width: 100px;background-color: rgba(0, 108, 169, 0.5);border-bottom: none;border-right: none; font-size: initial">单元</th>
              <th
                v-for="(item, index) in units"
                :key="index"
                :colspan="item.span"
                style="border:1px solid #ccc;background-color: rgba(0, 108, 169, 0.5); border-bottom: none;border-right: none; font-size: initial"
                :style="{width: `${(100 * item.span) - (index === 0 ? 1 : 0) }px`}"
              >{{ item.name }}</th>
            </tr>
          </table>
        </div>
        <div>
          <HotTable
            v-if="isRefesh"
            ref="handsontable"
            :settings="settings"
            style="height: calc(100vh - 230px);width: calc(100% - 10px);"
          />
        </div>
      </div>
      <!--<div style="position:absolute">
        <HotTable
          ref="handsontable"
          :settings="settings"
          :style="{height: `${tableHeight}px`, width: '100%'}"
        />
      </div>-->
    </el-main>
  </el-container>
</template>

<script>
import { HotTable } from '@handsontable/vue'
import { planRoom, delRoom, mergeRoom, splitRoom } from '@/api/baseManage/houseManage'
import 'handsontable/languages/zh-CN' // 引入中文语言包
export default {
  name: 'FloorPlan',
  components: {
    HotTable
  },
  props: {
    buildingData: { type: Object, default() { return {} } }
  },
  data() {
    const self = this
    return {
      mainInnerWidth: '100%',
      loading: false,
      /* 窗口开始标识 */
      dialogVisible: false,
      selectMode: '',
      selectLoading: false,
      /* 表格对象 */
      hot: {},
      /* 单元集合 */
      units: [],
      hasUnit: false,
      /* 选择平面图窗口开关标识*/
      dialogVisible1: false,
      /* 选择户型窗口开关标识*/
      dialogVisible2: false,
      /* 选中的索引 */
      selectCellIndex: [],
      tableHeight: 0,
      style: 'width: 100%; height: 100%;',
      /* 表格行头 */
      rowHeaders: [],
      isRefesh: false, // 刷新 HotTable组件 合并生效
      settings: {
        data: [[]],
        minRows: 0,
        minCols: 0,
        /* 表格列宽度*/
        colWidths: 100,
        /* 表格行头宽度*/
        rowHeaderWidth: 100,
        /* 固定行数 */
        // fixedRowsTop: 2,
        /* 固定列数 */
        // fixedColumnsLeft: 2,
        /* 行头集合 */
        rowHeaders: [],
        /* 列头集合 */
        colHeaders: [],
        /* 合并单元格集合 */
        mergeCells: [],
        // contextMenu:['mergeCells', 'unmergeCells'],
        language: 'zh-CN', // 声明用中文的语言包
        // 启用获取禁用复制粘贴功能
        copyPaste: false,
        /* 自定义菜单 */
        contextMenu: {},
        /* 单元格渲染 */
        cells: function(row, col, prop) {
          const cellProperties = {}
          cellProperties.editor = false
          // const floorIndex = self.rowHeaders.indexOf(6)
          const floorIndex = self.rowHeaders.indexOf(self.buildingData.salefloor)
          cellProperties.renderer = (instance, td, row, col, prop, value, cellProperties) => {
            let cellColor = '#606266'
            if (value) {
              if (value.layout_index && value.layout_index) {
                cellColor = '#32CD32'
              } else if (value.planar_graph_index && value.planar_graph_index) {
                cellColor = '#d5f60c'
              }
            } else { // 为空背景
              td.style.backgroundColor = '#EBEEF5'
            }
            const flag = value && value.fid && value.fid.length > 0
            td.innerHTML = flag ? `${value.fdisplayname}` : ''
            if (flag) {
              td.ondblclick = () => {
                self.cellDblclick(value)
              }
            }
            td.style.color = cellColor
            td.style.fontSize = '14px'
            td.style.textAlign = 'center'
            // td.style.backgroundColor = floorIndex === row ? '#aa0614' : 'transparent'
            td.style.display = 'table-cell'
            td.style.verticalAlign = 'middle'
            td.style.borderColor = '#ccc'
            td.style.borderBottomColor = floorIndex === row ? '#aa0614' : '#ccc'
            return td
          }
          return cellProperties
        },
        /* 单元合并之后 */
        afterMergeCells: function(cellRange, mergeParent, auto) {
          if (!auto) {
            // const toRow = cellRange.to.row; const toCol = cellRange.to.col
            // const fromRow = cellRange.from.row; const fromCol = cellRange.from.col
            // const indexArray = sameRow ? self.settings.data[toRow].slice(fromCol, toCol + 1).map(v => v.index)
            //   : self.settings.data.slice(fromRow, toRow + 1).map(v => v[toCol].index)
          }
        },
        /* 单元合并之前 */
        beforeMergeCells: function(cellRange, auto) {
          if (!auto) {
            const toRow = cellRange.to.row; const toCol = cellRange.to.col
            const fromRow = cellRange.from.row; const fromCol = cellRange.from.col
            const sameRow = toRow === fromRow
            const sameCol = toCol === fromCol
            this.getCellMeta()
            if (!sameRow && !sameCol) {
              self.$message.warning('只能合并同行或同列的单元格')
              return false
            }
            if (sameRow) {
              const cells = self.settings.mergeCells.filter(v => v.row === toRow && v.col >= fromCol && v.col <= toCol && v.colspan > 1)
              if (cells.length > 0) {
                self.$message.warning('不能合并已合并过的单元格')
                return false
              }
            }
            if (sameCol) {
              const cells = self.settings.mergeCells.filter(v => v.col === toCol && v.row >= fromRow && v.row <= toRow && v.rowspan > 1)
              if (cells.length > 0) {
                self.$message.warning('不能合并已合并过的单元格')
                return false
              }
            }
            const indexs = sameRow ? self.settings.data[toRow].slice(fromCol, toCol + 1).map(v => v.index).join()
              : self.settings.data.slice(fromRow, toRow + 1).map(v => v[toCol].index).join()
            self.cellMerge(indexs)
          }
        },
        /* 单元拆分之后 */
        afterUnmergeCells: function(cellRange, auto) {
          if (!auto) {
            const toRow = cellRange.to.row; const toCol = cellRange.to.col
            const fromRow = cellRange.from.row; const fromCol = cellRange.from.col
            const sameRow = toRow === fromRow
            // const sameCol = toCol === fromCol
            const indexArray = sameRow ? self.settings.data[toRow].slice(fromCol, toCol + 1).map(v => v.index)
              : self.settings.data.slice(fromRow, toRow + 1).map(v => v[toCol].index)
            self.cellSplit(indexArray[0])
          }
        },
        beforeUnmergeCells: function(cellRange, auto) {

        },
        /* 选中单元格 */
        afterSelection: function(row, column, row2, column2, preventScrolling, selectionLayerLevel) {
          const indexArray = []
          let c_row = row
          let c_column = column
          let c_row2 = row2
          let c_column2 = column2
          if (row > row2 || column > column2) {
            c_row = row2
            c_column = column2
            c_row2 = row
            c_column2 = column
          }
          self.settings.data.slice(c_row, c_row2 + 1).forEach(row => {
            row.slice(c_column, c_column2 + 1).forEach(col => {
              if (col && col.fid) {
                indexArray.push(col.fid)
              }
            })
          })
          if (self.selectLoading) {
            self.selectCellIndex = self.selectCellIndex.concat(indexArray)
          } else {
            self.selectCellIndex = indexArray
          }
        },
        /* Handsontable实例初始化 */
        afterInit: function() {
          self.hot = this
        },
        /* Handsontable表呈现之后 */
        afterRender: function(isForced) {
          const ele = document.getElementsByClassName('colHeader cornerHeader')
          if (ele.length > 0) {
            for (let i = 0; i < ele.length; i++) {
              ele[i].innerHTML = '编号'
            }
          }
        },
        /* 网格外部单击鼠标是否取消选择当前选择*/
        outsideClickDeselects: function(event) {
          self.selectCellIndex = []
          self.selectMode = ''
          return true
        }
      }
    }
  },
  watch: {
    buildingData(val) {
      this.selectMode = ''
      this.rowHeaders = []
      this.selectCellIndex = []
      this.fetchData()
    },
    'units.length'(val) {
      const tableHeight = this.$el.childNodes[1].clientHeight
      this.tableHeight = val === 0 ? tableHeight : tableHeight - 25
    }
  },
  created() {
    this.fetchData()
    const self = this
    const items = {}
    items.mergeRoom = {
      name: '合并房屋',
      callback: function(key, options) {
        self.cellMerge()
      }
    }
    items.splitRoom = {
      name: '拆分房屋',
      callback: function() {
        self.cellSplit()
      }
    }
    items.deleteRoom = {
      name: '删除房屋',
      callback: function() {
        self.deleteRoom()
      }
    }
    this.settings.contextMenu.items = items
  },
  mounted() {
    const ele = document.getElementsByClassName('colHeader cornerHeader')
    if (ele.length > 0) {
      for (let i = 0; i < ele.length; i++) {
        ele[i].innerHTML = '编号'
      }
    }
  },
  methods: {
    /**
     * 批量选择行
     * @param type 奇数或偶数
     */
    batchSelectionRow(type) {
      const coords = []
      type = this.selectMode === type ? '' : type
      this.selectMode = type
      const rowHeaders = this.rowHeaders
      if (type !== '') {
        for (let i = 0; i < rowHeaders.length; i++) {
          const rowHeader = rowHeaders[i]
          if ((type === 'even' && rowHeader % 2 === 0) ||
              (type === 'odd' && rowHeader > 0 && rowHeader % 2 !== 0)) {
            coords.push([i, 0, i, this.settings.data[i].length - 1])
          }
        }
      }
      this.selectCellIndex = []
      this.selectLoading = true
      this.hot.selectCells(coords, false, false)
      this.selectLoading = false
    },
    /**
     * 单元格双击
     * @param cellData 单元格数据
     */
    cellDblclick(cellData) {
      this.dialogVisible = true
      const buildingData = this.buildingData
      this.roomForm = Object.assign({}, cellData)
      this.roomForm.building_name = buildingData.building_name
      const unit_index = cellData.unit_index || 0
      if (unit_index !== 0 && buildingData.children && buildingData.children.length > 0) {
        const units = buildingData.children.filter(v => v.index === unit_index)
        if (units.length > 0) {
          this.roomForm.unit_name = units[0].unit_name
        }
      }
      this.$nextTick(() => {
        this.$refs.buildingRoomDetail.form = Object.assign({}, this.roomForm)
      })
    },
    /**
     * 删除房屋
     */
    deleteRoom() {
      const paramArr = [...this.selectCellIndex]
      this.$confirm('是否删除所选房屋?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRoom(paramArr).then(rv => {
          if (rv.code === 200) {
            this.fetchData()
            this.$message.success('删除成功！')
          }
        }).finally(() => {})
      }).catch(() => {
      })
    },
    /**
     * 查询数据
     */
    fetchData() {
      this.hasUnit = false
      this.isRefesh = false
      const baseInfo = this.buildingData
      if (baseInfo.type === undefined) return
      const params = {}
      if (baseInfo.type === 'building') {
        params.fbuildingid = baseInfo.fid
      } else {
        params.fbuildingid = baseInfo.fbuildingid
        params.fbuildunitid = baseInfo.fid
      }
      this.loading = true
      planRoom(params).then(res => {
        if (res.code === 200) {
          const rv = res.data
          this.isRefesh = true
          let colHeaders = []
          this.rowHeaders = rv.floorArr || []
          const tableData = rv.table || []
          const roomSortArr = rv.roomSortArr || []
          let insertIndex = 0
          roomSortArr.forEach((v) => {
            if (v.length === 0) {
              v = ['-']
              tableData.map(row => {
                return row.splice(insertIndex, 0, {})
              })
            }
            const length = v.length
            insertIndex += length
            colHeaders = colHeaders.concat(v)
          })
          const unitArr = rv.unitArr || []
          const units = []
          unitArr.forEach((v, index) => {
            let length = roomSortArr[index].length
            length = length === 0 ? 1 : length
            if (v.fnameL2) {
              units.push({ name: v.fnameL2, span: length })
            }
          })
          this.units = units
          if (this.units.length > 0) {
            setTimeout(() => {
              this.hasUnit = true
            }, 1000)
          }
          if (units.length > 0) {
            const div = document.getElementById('mainId')
            const mainWidth = div.style.width || div.clientWidth || div.offsetWidth || div.scrollWidth
            const num = parseInt(mainWidth / 100)
            if (num < colHeaders.length + 1) { // '1'为行表头'层'
              this.mainInnerWidth = (colHeaders.length + 1) * 100 + 10 + 'px'
            } else {
              this.mainInnerWidth = '100%'
            }
          } else {
            this.mainInnerWidth = '100%'
          }
          const settings = Object.assign(this.settings, {
            rowHeaders: this.rowHeaders.map(v => `${v}层`),
            colHeaders: colHeaders,
            mergeCells: rv.mergeCell || [],
            data: tableData
          })
          this.$nextTick(() => { // 处理莫名出现竖向滚动条
            this.hot.destroyEditor(false, false)
            this.hot.updateSettings(settings, true)
          })
        }
      }).finally(() => {
        this.loading = false
      })
    },
    cellMerge() {
      this.loading = true
      mergeRoom(this.selectCellIndex).then(rv => {
        if (rv.code === 200) {
          this.fetchData()
          // this.selectCellIndex = [rv.data]
          this.$message.success('合并单元格成功！')
        } else {
          this.$message.warning('合并单元格失败！')
        }
      }).finally(() => {
        this.loading = false
      })
    },
    cellSplit() {
      if (this.selectCellIndex.length === 1) {
        splitRoom({ fid: this.selectCellIndex[0] }).then(rv => {
          if (rv.code === 200) {
            this.fetchData()
            this.$message.success('拆分单元格成功！')
          } else {
            this.$message.warning('拆分单元格失败！')
          }
        })
      } else {
        this.$message.success('请选择已合并需要拆分')
      }
    }
  }
}
</script>
<style src="../../../../node_modules/handsontable/dist/handsontable.full.css">
/* All headers */
.handsontable th {
  background-color: #F00;
}

</style>
<style>
.handsontable table.htCore tr {
    background-color: transparent !important;
}
.handsontable th {
  color: #FFF;
  background-color: rgba(0, 108, 169, 0.5);
  width: 100px;
}
.handsontable tr:first-child th:first-child {
  border-right: none;
}
.handsontable tbody th.ht__highlight, .handsontable thead th.ht__highlight {
  background-color: rgba(0, 108, 169, 0.5);
}
.htItemWrapper {
  color: #00adff;
}
.handsontable td.area:before {
  background-color: rgba(58, 121, 47, 0.5);
  opacity: 1
}
</style>
